package com.ai.bitcoin.jpa.dao;

import com.ai.bitcoin.constant.Bcc;
import com.ai.bitcoin.jpa.entity.BccPriceInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Jason
 * @date 2018/4/6
 **/
public interface BccPriceInfoDao extends JpaRepository<BccPriceInfo, String> {
    BccPriceInfo save(BccPriceInfo bccPriceInfo);

    Page<BccPriceInfo> findByBatchNo(String batchNo, Pageable pageable);

    Page<BccPriceInfo> findByBccId(String bccId, Pageable pageable);

    Page<BccPriceInfo> findByBccIdAndPriceTimestampGreaterThan(String bccId, Date time, Pageable pageable);

    @Query(nativeQuery = true, value = "delete  from bcc_price_info where record_state ='" + Bcc.RecordState.UN_PUBLISH + "'")
    @Modifying
    @Transactional
    void deleteNoPublish();

    void deleteByBatchNo(String batchNo);

    List<BccPriceInfo> findByBccIdAndBatchNo(String bccId, String batchNo);

    List<BccPriceInfo> findByBccIdAndBatchNoAndRecordState(String bccId, String batchNo, String recordState);

    List<BccPriceInfo> findByBccIdAndRecordState(String bccId, String recordState);

    List<BccPriceInfo> findByBatchNo(String batchNo);

    @Query(nativeQuery = true, value = "SELECT * FROM bcc_price_info WHERE bcc_id = ?1 AND record_state =?2 ORDER BY create_time desc limit 1")
    List<BccPriceInfo> findOneByBccIdAndRecordStateOrderByCreateTimeDesc(String bccId, String recordState);


    @Query(nativeQuery = true, value = "SELECT * FROM bcc_price_info WHERE bcc_Id =:bccId AND price_timestamp>:fr AND price_timestamp< :to ORDER BY price_timestamp limit 1")
    BccPriceInfo findOneByBccIdBetween(@Param("bccId") String bccId, @Param("fr") Date fr, @Param("to") Date to);

    @Query(nativeQuery = true, value = "update bcc_price_info set record_state ='" + Bcc.RecordState.PUBLISH + "' where batch_no = ?1")
    @Modifying
    void update2Publish(String unPublishBatch);

    @Query(nativeQuery = true, value = "delete  from bcc_price_info where batch_no<> ?1 or record_state ='" + Bcc.RecordState.PUBLISH + "'")
    @Modifying
    void deleteOldPublish(String publishBatch);


    @Query(nativeQuery = true, value = "DELETE FROM  bcc_price_info WHERE create_time < DATE_SUB(CURDATE(),INTERVAL 1 DAY)")
    @Modifying
    void delete2DayBefore();

    BccPriceInfo findTop1ByBccIdOrderByPriceTimestampDesc(String bccId);
}
